$(function () {
    /*
     * 添加规则
     */
    $(".save_rule").on("click", function () {
        var title = $.trim($("input[name='title']").val());
        var department_id = $("input[name='title']").attr("data-department_id");
        var rule_content = $.trim($("#editor").html());
        if (title == "") {
            crm.alert("管理制度的标题不能为空", "error");
        } else if (rule_content.length <= 0) {
            crm.alert("管理制度的内容不能为空", "error");
        } else {
            var data = {
                "title": title,
                "rule_content": rule_content,
                "department_id": department_id
            };
            var request_url = package_url("public_module/rule/confirm_rule");
            var order_url = package_url("public_module/rule/show_rule") + "/department_id/" + department_id;
            crm_ajax(data,request_url,function (res) {
                if(res){
                    crm.alert("添加成功", "success", function () {
                        location.href = order_url;
                    });
                }else{
                    crm.alert("添加失败", "error");
                }
            })
        }
    })

    /*
     * 确认修改规则页面
     */
    $(".change_rule").on("click",function () {
        var title = $.trim($("input[name='title']").val());
        var rule_content = $.trim($("#editor").html());
        var rule_id = $(this).attr("data-ruleId");
        var department_id = $(this).attr("data-departmentId");
        var data = {
            "rule_id": rule_id,
            "title": title,
            "rule_content": rule_content
        };
        var request_url = package_url("public_module/rule/change_rule");
        crm_ajax(data,request_url,function (res) {
            if(res){
                crm.alert("修改成功", "success", function () {
                    location.href = "/public_module/rule/show_rule/department_id/" + department_id;
                });
            }else{
                crm.alert("修改失败", "error");
            }
        })
    })

    /*
     * 删除规则
     */
    $(".rule_delete").on("click", function () {
        var now_rule = $(this).parent().parent().parent().parent().attr("data-id");
        var now_department = $(this).parent().parent().parent().parent().attr("data-department");
        var request_url = package_url("public_module/rule/delete_rule");
        crm.alert("确认删除么?", "warning", function () {
            var data = {
                'id': now_rule
            }
            crm_ajax(data, request_url, function (res) {
                if (res) {
                    crm.alert("删除成功", "success", function () {
                        location.href = "/public_module/rule/show_rule/department_id/" + now_department;
                    });
                } else {
                    crm.alert("删除失败", "error");
                }
            })
        })
    })
})
